package code.lewdy.db;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;

import com.lt.member.Member;
import com.lt.member.MemberService;
import com.lt.member.MemberStatistics;

import dao.HibernateSessionFactory;

public class HibernateTemple {

	public static void main(String[] args) {
		// System.out.println(load(Member.class, 3));
		//MemberStatistics mss = (MemberStatistics) loadUnique("from MemberStatistics where ownerId=31");
		//System.out.println(mss.getOwnerName());
		System.out.println(list("from Member").size());
	}
	
	public static Object getUniqueResult(String hsql){
		Session s = HibernateSessionFactory.getSession();
		s.beginTransaction();
		Object obj = s.createQuery(hsql).uniqueResult();
		s.getTransaction().commit();
		s.close();
		return obj;
	}
	
	public static List<?> list(String hsql){
		Session s = HibernateSessionFactory.getSession();
		s.beginTransaction();
		List list = s.createQuery(hsql).list();
		s.getTransaction().commit();
		s.close();
		return list;
	}
	
	/**
	 * load data for an entity
	 * 
	 * @param c
	 * @param id
	 * @return
	 */
	public static Object load(Class<?> c, Serializable id) {
		Session s = HibernateSessionFactory.getSession();
		s.beginTransaction();
		Object obj = s.get(c, id);
		s.getTransaction().commit();
		s.close();
		return obj;
	}

	/**
	 * 更新实体
	 * 
	 * @param obj
	 */
	public static void update(Object obj) {
		if(obj.getClass().getName().equals(Member.class.getName())){
			MemberService.updateMember((Member)obj);
		}else{
			Session s = HibernateSessionFactory.getSession();
			s.beginTransaction();
			s.update(obj);
			s.getTransaction().commit();
			s.close();
		}
	}

	public static Long save(Object obj) {
		Session s = HibernateSessionFactory.getSession();
		s.beginTransaction();
		Long id = Long.parseLong("" + s.save(obj));
		s.getTransaction().commit();
		s.close();
		return id;
	}

	/**
	 * 根据hsql load实体
	 * 
	 * @param hsql
	 * @return
	 */
	public static Object loadUnique(String hsql) {
		Session s = HibernateSessionFactory.getSession();
		s.beginTransaction();
		Object obj = s.createQuery(hsql).uniqueResult();
		s.getTransaction().commit();
		s.close();
		return obj;
	}
}
